<?php

namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Session;

// 购买支付
class Buy extends BaseController
{
    // 下单
    public function dobuy()
    {
        $user = Session::get('user');
        !$user && die(json_encode(['code' => 1, 'msg' => '请先登录']));
        $sku_arr = input('post.sku_arr');
        $data['uid'] = $user['id'];
        $data['ord_no'] = $user['id'] . time() . rand(100, 999);
        $skus = Db::table('product_sku')->whereIn('out_no', array_column($sku_arr, 'sku_out_no'))->select()->map(function ($item) use ($sku_arr) {
            $arr = array_combine(array_column($sku_arr, 'sku_out_no'), array_column($sku_arr, 'count'));
            $item['count'] = $arr[$item['out_no']];
            return $item;
        });
        $data['money'] = $skus->reduce(function ($res, $next) {
            $res += $next['price'] * $next['count'];
            return $res;
        }, 0);
        // $data['express_no'] = '';
        // $data['express_name'] = '';
        $data['add_time'] = time();
        Db::table('orders')->insert($data);
        $products = $skus->reduce(function ($res, $next) use ($data) {
            $res[] = [
                'ord_no' => $data['ord_no'],
                'sku_out_no' => $next['out_no'],
                'count' => $next['count'],
                'price' => $next['price'],
            ];
            return $res;
        }, []);
        Db::table('orders_product')->insertAll($products);
        // 微信支付
        $ord_title_arr = Db::table('product')->whereIn('id', $skus->column('pro_id'))->column('title');
        $ord_title = mb_strimwidth(implode(';', $ord_title_arr), 0, 128, '', 'utf-8');
        $ord_no = $data['ord_no'];
        $ord_money = $data['money'] * 100;
        $url2 = $this->wxpay($ord_title, $ord_no, $ord_money);
        exit(json_encode(['code' => 0, 'msg' => '保存成功', 'url2' => $url2, 'ord_no' => $ord_no]));
    }

    // 我的订单中支付订单
    public function pay() {
        $user = $this->app->session->get('user');
        $id = (int)input('post.id');
        $item = Db::table('orders')->where('uid', $user['id'])->where('id', $id)->find();
        !$item && exit(json_encode(['code' => 1, 'msg' => '数据错误']));
        $ord_no = $item['ord_no'];
        $orders_product = Db::table('orders_product')->whereIn('ord_no', $ord_no)->select()->toArray();
        $product_sku = Db::table('product_sku')->whereIn('out_no', array_column($orders_product, 'sku_out_no'))->select()->toArray();
        $ord_title_arr = Db::table('product')->whereIn('id', array_column($product_sku, 'pro_id'))->column('title');
        $ord_title = mb_strimwidth(implode(';', $ord_title_arr), 0, 128, '', 'utf-8');
        $ord_money = $item['money'] * 100;
        $url2 = $this->wxpay($ord_title, $ord_no, $ord_money);
        exit(json_encode(['code' => 0, 'msg' => '', 'url2' => $url2, 'ord_no' => $ord_no]));
    }

    // 微信支付
    private function wxpay($ord_title, $ord_no, $ord_money)
    {
        $sdkpath = $this->app->getRootPath() . 'vendor/wxpaysdk';
        require_once $sdkpath . "/lib/WxPay.Api.php";
        require_once $sdkpath . "/example/WxPay.NativePay.php";
        // require_once $sdkpath . '/example/log.php';

        //初始化日志
        // $logHandler = new \CLogFileHandler($sdkpath ."/logs/" . date('Y-m-d') . '.log');
        // $log = \Log::Init($logHandler, 15);

        $notify = new \NativePay();
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($ord_title);
        $input->SetAttach($ord_title);
        $input->SetOut_trade_no($ord_no); // 订单号
        $input->SetTotal_fee($ord_money); // 费用，单位：分
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag($ord_title);
        $input->SetNotify_url("https://domain/buy/notify"); // 支付完成后通知
        $input->SetTrade_type("NATIVE");
        $input->SetProduct_id("123456789");

        $result = $notify->GetPayUrl($input);
        // dump($result);
        // 测试
        $result = ['return_code' => 'success', 'return_msg' => '', 'code_url' => 'weixin:paytest'];
        $url2 = $result["code_url"];
        return $url2;
    }

    // 展示二维码
    public function showQrcode()
    {
        $data['url2'] = input('get.url2');
        $data['ord_no'] = input('get.ord_no');
        return view('/buy/showQrcode', $data);
    }

    // 生成二维码图片
    public function createQrImg()
    {
        require_once $this->app->getRootPath() . 'vendor/wxpaysdk/example/phpqrcode/phpqrcode.php';
        $url = urldecode($_GET["data"]);
        if (substr($url, 0, 6) == "weixin") {
            \QRcode::png($url);
        } else {
            header('HTTP/1.1 404 Not Found');
        }
    }

    // 检查订单是否支付
    public function chk_ispay()
    {
        $ord_no = input('get.ord_no');
        $item = Db::table('orders')->where('ord_no', $ord_no)->find();
        $item && $item['status'] == 1 && exit(json_encode(['code' => 0, 'msg' => '支付成功']));
        exit(json_encode(['code' => 1, 'msg' => '还未支付']));
    }

    // 支付完成定期通知
    public function notify()
    {
        // 接收微信推送的数据
        $data = file_get_contents('php://input');
        // 将接收的数据写入日志文件 
        !is_dir('wxPay') && @mkdir('wxPay', 0700, true);
        !is_dir('wxPay/' . date('Ym')) && @mkdir('wxPay/' . date('Ym'), 0700, true);
        $path = 'wxPay/' . date('Ym') . '/' . date('Ymd') . '.txt';
        // 处理微信返回的xml格式数据 转换为 数组
        libxml_disable_entity_loader(true);
        $data = json_decode(json_encode(simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        file_put_contents($path, date('Y-m-d H:i:s') . "\n Content:" . json_encode($data) . "\n\n", FILE_APPEND);
        /**
         * appid => wx999916f37......
         * attach => 商品标题
         * bank_type => OTHERS
         * cash_fee => 1
         * fee_type => CNY
         * is_subscribe => N
         * mch_id => 16098.....
         * nonce_str => 1g3pkhrzzalqeij9rrml8x65wkmpz1r
         * openid => omKRv6GSDk......
         * out_trade_no => 1162618001669
         * result_code => SUCCESS
         * return_code => SUCCESS
         * sign => 3DSFRRDF983FFD934LDSF9323M42832M23......
         * time_end => 20210713205652
         * total_fee => 1
         * trade_type => NATIVE
         * transaction_id => 420000123420217131094283958
         */
        if ($data['result_code'] != 'SUCCESS') return;
        // xml反馈微信服务器
        $xml = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        $out_no = $data['out_trade_no'];
        // 已经支付成功时
        $item = Db::table('orders')->where('ord_no', $out_no)->find();
        $item && $item['status'] == 1 && exit($xml);
        // 优惠券抵扣
        // ...
        // 修改订单状态
        Db::table('orders')->where('ord_no', $out_no)->update(['status' => 1, 'transaction_id' => $data['transaction_id']]);
        exit($xml);
    }
}
